﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SisGAC.Models;

namespace SisGAC.Controllers
{
    public class CongressosController : Controller
    {
        private SisgacContext db = new SisgacContext();

        //
        // GET: /Congressos/

        public ActionResult Index()
        {
            List<Congresso> congressos = db.Congressos.ToList();
            return View(congressos);
        }

        [Authorize(Roles="Admin")]
        public ActionResult Cadastro(int id = 0)
        {
            CongressoViewModel model = new CongressoViewModel();
            model.Congresso = new Congresso();

            model.Coordenadores = new SelectList(db.Pessoas.Where(p => p.Coordenador), "PessoaId", "Nome");

            if (id > 0)
            {
                model.Congresso = db.Congressos.Find(id);
                if (model.Congresso == null)
                    return HttpNotFound();
                model.CoordenadorId = model.Congresso.Coordenador.PessoaId;
            }

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles="Admin")]
        public ActionResult Cadastro(CongressoViewModel model)
        {
            if (model.CoordenadorId > 0)
            {
                Pessoa coordenador = db.Pessoas.Find(model.CoordenadorId);
                model.Congresso.Coordenador = coordenador;
            }

            if (model.Congresso.CongressoId > 0)
            {
                db.Entry(model.Congresso).State = EntityState.Modified;
            }
            else
            {
                db.Congressos.Add(model.Congresso);
            }
            db.SaveChanges();

            return RedirectToAction("Index");

        }

    }
}
